package com.library.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.library.bean.ReaderCard;
import com.library.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Calendar;
import java.util.Date;
import java.util.Optional;


public class CommonUtils {

    private final static Logger log = LoggerFactory.getLogger(LoginService.class);


    public static String writeValueAsString(Object obj) {
        if(obj == null){
            return "";
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(obj);
            return s;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static Object getSession(){
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attrs != null) {
            HttpServletRequest request = attrs.getRequest();
            HttpSession session = request.getSession();
            // 使用session对象
            Object attribute = session.getAttribute(CommonConstant.SESSION_READERCARD);
            return attribute;
        }
        return null;
    }

    public static ReaderCard getLoginReaderCard(){
        Object attribute = CommonUtils.getSession();
        ReaderCard readerCard = (ReaderCard)attribute;
        log.info("{}", CommonUtils.writeValueAsString(readerCard));
        return readerCard;
    }

    public static String getLoginReaderCardRole(){
        String loginReaderCardRole = Optional.ofNullable(CommonUtils.getLoginReaderCard()).map(e->e.getRole()).orElse("");
        if(StringUtils.isEmpty(loginReaderCardRole)) return null;
        return loginReaderCardRole;
    }

    public static Calendar getCalendarYYYYMMDD(Date date) {
        // 创建一个 Calendar 对象，并将其时间设置为 Date 对象的时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        // 将时、分、秒设置为 0
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }

}
